// NewCivWindow.xaml.cs
//
// Copyright (c) 2007 Mike Strobel
//
// This source code is subject to the terms of the Microsoft Reciprocal License (Ms-RL).
// For details, see <http://www.opensource.org/licenses/ms-rl.html>.
//
// All other rights reserved.

using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;

using Avalon.Windows.Controls;

using Supremacy.Entities;
using Supremacy.Game;
using Supremacy.Tech;

namespace Supremacy.Editor
{
    /// <summary>
    /// Interaction logic for NewCivWindow.xaml
    /// </summary>

    public partial class NewCivWindow
    {
        private bool _bindShortName = true;

        public NewCivWindow()
        {
            InitializeComponent();

            RaceList.ItemsSource = EditorApp.Current.EditorContext.Races;
            RaceList.DisplayMemberPath = "PluralName";
            RaceList.SelectedIndex = 0;
            RaceList.SelectionChanged += RaceList_SelectionChanged;

            ShortNameText.TextChanged += ShortNameText_TextChanged;
            ShortNameText.LostFocus += ShortNameText_LostFocus;
            NewRaceButton.Checked += NewRaceButton_Checked;
            
            Loaded += NewCivWindow_Loaded;
        }

        void ShortNameText_LostFocus(object sender, RoutedEventArgs e)
        {
            _bindShortName = false;
        }

        void ShortNameText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_bindShortName)
            {
                IdentityText.Text = NameToIdentity(ShortNameText.Text);
                LongNameText.Text = ShortNameText.Text.Trim();
            }
        }

        void RaceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Race race = RaceList.SelectedItem as Race;
            if (race != null)
            {
                if (IdentityText.Text.Length == 0)
                {
                    IdentityText.Text = race.Key;
                    if (ShortNameText.Text.Length == 0)
                    {
                        ShortNameText.Text = race.PluralName;
                        if (LongNameText.Text.Length == 0)
                            LongNameText.Text = race.PluralName;
                    }
                }
            }
        }

        void NewCivWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShortNameText.Focus();
        }

        void NewRaceButton_Checked(object sender, RoutedEventArgs e)
        {
            if ((RaceIdentityText.Text.Length == 0) && (IdentityText.Text.Length > 0))
                RaceIdentityText.Text = IdentityText.Text;
            if ((RaceNameText.Text.Length == 0) && (ShortNameText.Text.Length > 0))
                RaceNameText.Text = ShortNameText.Text;
        }

        void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            string id = IdentityText.Text.ToUpperInvariant().Trim();
            string shortName = ShortNameText.Text.Trim();
            string longName = LongNameText.Text.Trim();
            if (id.Length == 0)
            {
                TaskDialog.Show(
                    "You must enter an identity.",
                    "Invalid Identity",
                    EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                return;
            }
            if (shortName.Length == 0)
            {
                TaskDialog.Show(
                    "You must enter a short name.",
                    "Invalid Name",
                    EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                return;
            }
            if (longName.Length == 0)
            {
                TaskDialog.Show(
                    "You must enter a long name.",
                    "Invalid Name",
                    EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                return;
            }
            if (!EnsureUniqueCivIdentity(id))
            {
                TaskDialog.Show(
                    "A civilization with the identity " + id + " already exists.",
                    "Identity Conflict",
                    EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                return;
            }
            if (ExistingRaceButton.IsChecked.Value)
            {
                DialogResult = true;
            }
            else
            {
                string raceId = RaceIdentityText.Text.ToUpperInvariant().Trim();
                string raceName = RaceNameText.Text.Trim();
                if (raceId.Length == 0)
                {
                    TaskDialog.Show(
                        "You must enter a race identity.",
                        "Invalid Identity",
                        EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                    return;
                }
                if (raceName.Length == 0)
                {
                    TaskDialog.Show(
                        "You must enter a race name.",
                        "Invalid Name",
                        EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                    return;
                }
                if (!EnsureUniqueRaceIdentity(raceId))
                {
                    TaskDialog.Show(
                        "A race with the identity " + raceId + " already exists.",
                        "Identity Conflict",
                        EditorApp.Current.MainWindow.Title,
                    TaskDialogButtons.OK,
                    TaskDialogIcon.Warning);
                    return;
                }
                DialogResult = true;
            }
        }

        private static bool EnsureUniqueCivIdentity(string id)
        {
            return !EditorApp.Current.EditorContext.Civilizations.Contains(id);
        }
        
        private static bool EnsureUniqueRaceIdentity(string id)
        {
            return !EditorApp.Current.EditorContext.Races.Contains(id);
        }

        public static Civilization GetNewCiv()
        {
            NewCivWindow dialog = new NewCivWindow();
            dialog.Owner = EditorApp.Current.MainWindow;
            dialog.ShowDialog();
            if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
            {
                Race race;
                Civilization civ;
                string civId = dialog.IdentityText.Text.Trim().ToUpper();

                if (dialog.ExistingRaceButton.IsChecked.Value)
                {
                    race = dialog.RaceList.SelectedItem as Race;
                }
                else
                {
                    string raceId = dialog.RaceIdentityText.Text.Trim().ToUpper();
                    string raceName = dialog.RaceNameText.Text.Trim();
                    race = new Race();
                    race.Key = raceId;
                    race.PluralName = raceName;
                    race.SingularName = (raceName.EndsWith("s")) ? raceName.Substring(0, raceName.Length - 1) : raceName;
                    EditorApp.Current.EditorContext.Races.Add(race);
                    EditorApp.Current.EditorContext.OnAddingNew(race);
                }

                civ = new Civilization(civId, race);
                civ.CivID = EditorApp.Current.EditorContext.Civilizations.GetNewCivID();
                civ.ShortName = dialog.ShortNameText.Text.Trim();
                civ.LongName = dialog.LongNameText.Text.Trim();

                EditorApp.Current.EditorContext.Civilizations.Add(civ);

                if (!EditorApp.Current.EditorContext.CivTechTrees.ContainsKey(civ.Key))
                {
					EditorApp.Current.EditorContext.CivTechTrees[civ.Key] = new TechTree();
                }

                return civ;
            }
            else
            {
                return null;
            }
        }

        private static string NameToIdentity(string name)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < name.Length; i++)
            {
                if (Char.IsLetter(name[i]))
                    sb.Append(name[i]);
            }
            return sb.ToString().ToUpperInvariant();
        }
    }
}